package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryBrandService categoryBrandService;
    //普通分页查询
//    @Override
//    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
//        // 1.分页信息的健壮性处理
//        page = Math.min(page, 100);
//        rows = Math.max(rows, 5);
//        // 2.分页
//        Page<Brand> info = new Page<>(page, rows);
//        // 3.判断key是否存在
//        boolean isKeyExists = StringUtils.isNoneBlank(key);
//        // 4.如果key存在，添加like和eq的查询条件，否则不添加
//        query().like(isKeyExists, "name", key)
//                .or()
//                .eq(isKeyExists, "letter", key)
//                .page(info);
//        // 5.封装结果
//        List<Brand> list = info.getRecords();
//        return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(list));
//    }
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {

        IPage<Brand> iPage = new Page<>(page,rows);
        boolean b = StringUtils.isBlank(key);//isBlank 意思是为空 返回true
        //分页查询,自动回填结果
        //select * from tb_brand [where name like %key% or letter = key] limit x,y;
        //只有b为true，like条件才会出现在sql中
        page(iPage,new QueryWrapper<Brand>()
                .like(!b,"name",key)
                .or()
                .eq(!b,"letter",key)

        );
        //封装PageDTO<BrandDTO>,返回brand的查询结果
        return new PageDTO<BrandDTO>(iPage.getTotal(),iPage.getPages(),BrandDTO.convertEntityList(iPage.getRecords()));
    }

    @Override
    public List<BrandDTO> queryBrandByIds(List<Long> ids) {
        List<Brand> brands = brandService.listByIds(ids);
        return BrandDTO.convertEntityList(brands);
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long c_id) {

        return BrandDTO.convertEntityList(this.getBaseMapper().queryBrandByCategory(c_id));
    }

    @Override
    public BrandDTO queryBrandById(Long id) {

        return new BrandDTO(getById(id));
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        //从DTO中 拿到brand
        Brand brand = brandDTO.toEntity(Brand.class);
        //添加品牌表数据
        save(brand);
        //添加中间表数据  category_id 和 brand_id(brandDTO  中包含)
        saveCategoryBrand(brandDTO.getCategoryIds(), brand);

    }

    private void saveCategoryBrand(List<Long> categoryIds, Brand brand) {
        List<CategoryBrand> list = categoryIds
                .stream()
                .map(id -> CategoryBrand
                        .of(id, brand.getId()))
                .collect(Collectors
                        .toList());

        //批量写入 中间表
        categoryBrandService.saveBatch(list);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);

        // 保存主表信息
        updateById(brand);

        //接下来要修改中间表信息
        //先删除之前的中间表信息  delete from tb_category_brand where brand_id =  #{id}
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brand.getId()));
        //保存中间表信息
        brandDTO.getCategoryIds();
        saveCategoryBrand(brandDTO.getCategoryIds(), brand);
    }

    @Override
    public void deleteBrandById(Long id) {
        //根据id删除主表信息
        removeById(id);
        //删除中间表信息
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
    }


}
